import * as mqtt from "mqtt/dist/mqtt.min";

export function useMqtt() {
    var client;
    const URL = 'wss://mqtt.change90.com:1888'
    // const URL = 'wss://mqtt-cn.change90.com:1888'
    const OPTIONS = {
        port: 1888,
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: 'mqttjs_' + Math.random().toString(16).substring(2, 8),
        username: 'change90',
        password: 'change90@',
    }
    var timer
    // 初始化
    function init(topics = [], callback) {
        const that = this
        client = mqtt.connect(URL, OPTIONS);
        console.log('ccc==', client, topics)
        if (topics.length > 0) {
            topics.forEach((item) => {
                listen(item)
            })
            client.on('message', callback);
        }
        if (!timer) {
            timer = setInterval(() => {
                client.publish('/1/keepalive/'+OPTIONS.clientId, '{"action":"keepalive"}', { qos: 0 }, err => {
                    console.log('err==', err)
                });
            }, 60000);
        }
    }
    function listen(topic) {
        client.on('connect', () => {
            client.subscribe(topic, (error) => {
                if (!error) {
                    console.log('订阅成功');
                } else {
                    console.log('订阅失败');
                }
            });
        });
    }
    function publish(topic, msg) {
        client.on('connect', () => {
            client.publish(topic, msg, { qos: 1 }, err => {
                console.log('err==', err)
            });
        });
    }
    return {
        init,
        publish
    }
}